package com.espirit.eap;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.Session;
import org.springframework.stereotype.Service;

import com.espirit.eap.manager.I18n;
import com.espirit.eap.manager.I18nService;
import com.espirit.eap.pagelayout.ModelService;
import com.googlecode.cswish.exception.ApplicationException;
import com.googlecode.cswish.struts.spring.BeanIntrospector;
import com.googlecode.cswish.util.ClassUtil;

@Service
public class AppExceptionUtils {
	@Resource
	ModelService modelService;
	
	@Resource
	I18nService i18nService;
	
	@Resource
	BeanIntrospector beanIntrospector;
	
	@PersistenceContext(unitName="espirit")
	protected EntityManager em;
	
	public <T> void raiseError(T model, String property, String i18nKey){
		String className = ClassUtil.getClassName(model);
		String simpleModelName = beanIntrospector.getSimpleName(className);
		String i18n = modelService.getModelFieldI18n(simpleModelName, property);
		I18n fieldI18n = i18nService.getI18n(i18n, true);
		String error = fieldI18n.getName();
		
		throw new ApplicationException(i18nKey, error);
	}
	
	public Session getSession(){
		return (Session)em.getDelegate();
	}
}
